package homework.chatone;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ChatClient01 {
    private static Socket socket;

    public ChatClient01() {
        try {
            socket = new Socket("127.0.0.1", 8088);
            System.out.println("连接成功...");
        } catch (IOException e) {
            System.out.println("连接失败...");
            e.printStackTrace();
            System.exit(1);
        }

    }

    class ServerHandler implements Runnable{
        BufferedReader br;
        @Override
        public void run() {
            try {
                br = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8)
                );

                String data;
                while ((data=br.readLine())!=null){
                    System.out.println(data);
                }

            } catch (IOException e) {
                try {
                    br.close();
                    socket.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }

        }
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);
        PrintWriter pw = null;
        try {
                pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)
                        ), true);


                while (true){
                    System.out.println("请输入昵称:");
                    String name = scanner.nextLine();
                    if (name.trim().isEmpty()){
                        System.out.println("昵称不能为空");
                        continue;
                    }
                    pw.println(name);
                    break;
                }

                new Thread(new ServerHandler()).start();
                System.out.println("发送消息");
                while (true) {
                    String chat = scanner.nextLine();
                    if ("exit".equalsIgnoreCase(chat)) {
                        System.out.println("退出聊天室...");
                        break;
                    }
                    pw.println(chat);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(pw!=null)pw.close();
            if (scanner!=null)scanner.close();
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        new ChatClient01().start();
    }

}
